package timing.ukulele.third.msgChannel.handle.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Throwables;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import timing.ukulele.third.dictionary.msg.MsgChannelType;
import timing.ukulele.third.msgChannel.handle.BaseHandler;
import timing.ukulele.third.msgChannel.model.RecallTaskInfo;
import timing.ukulele.third.msgChannel.model.SendTaskInfo;
import timing.ukulele.third.msgChannel.model.content.MiniProgramContentModel;
import timing.ukulele.third.msgChannel.param.HandleMessageBaseResponse;
import timing.ukulele.third.msgChannel.utils.AccountUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 微信小程序发送订阅消息
 * https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-message-management/subscribe-message/sendMessage.html
 * @author zh
 */
@Component
@Slf4j
public class MiniProgramAccountHandler extends BaseHandler {

    @Autowired
    private AccountUtils accountUtils;

    public MiniProgramAccountHandler() {
        channelCode = MsgChannelType.MINI_PROGRAM.getCode();
    }

    @Override
    public HandleMessageBaseResponse send(SendTaskInfo taskInfo) {
        // 构造返回值
        HandleMessageBaseResponse result = new HandleMessageBaseResponse();
        try {
            // 获取微信小程序账号信息
            MiniProgramContentModel contentModel = (MiniProgramContentModel) taskInfo.getContentModel();
            WxMaService wxMaService = accountUtils.getAccountById(taskInfo.getSendAccountId(), WxMaService.class);
            // 请求发送消息
            WxMaSubscribeMessage message = assembleReq(taskInfo.getReceiver(), contentModel);
            wxMaService.getSubscribeService().sendSubscribeMsg(message);
            result.setHandleFlag(true);
        } catch (WxErrorException e) {
            log.error("MiniProgramAccountHandler#send fail:{},params:{}", e.getError().getErrorMsg(), JSON.toJSONString(taskInfo));
            result.setHandleFlag(false);
        } catch (Exception e) {
            log.error("MiniProgramAccountHandler#send fail:{},params:{}", Throwables.getStackTraceAsString(e), JSON.toJSONString(taskInfo));
            result.setHandleFlag(false);
        }
        return result;
    }

    /**
     * 组装发送模板信息参数
     * @param receiver 接收信息者
     * @param contentModel 消息参数信息
     * @return
     */
    private WxMaSubscribeMessage assembleReq(Set<String> receiver, MiniProgramContentModel contentModel) {
        return WxMaSubscribeMessage.builder()
                .toUser(CollUtil.getFirst(receiver.iterator()))
                .data(getWxMaTemplateData(contentModel.getMiniProgramParam()))
                .templateId(contentModel.getTemplateId())
                .page(contentModel.getPage())
                .build();
    }

    /**
     * 构建订阅消息参数
     * @param data 模板参数
     * @returnp
     */
    private List<WxMaSubscribeMessage.MsgData> getWxMaTemplateData(Map<String, String> data) {
        List<WxMaSubscribeMessage.MsgData> templateDataList = new ArrayList<>(data.size());
        data.forEach((k, v) -> templateDataList.add(new WxMaSubscribeMessage.MsgData(k, v)));
        return templateDataList;
    }

    /**
     * 微信小程序发送订阅消息 不支持撤回
     * @param recallTaskInfo
     */
    @Override
    public HandleMessageBaseResponse recall(RecallTaskInfo recallTaskInfo) {
        return HandleMessageBaseResponse.builder().handleFlag(true).build();
    }

}

